package com.smartleanx.module.hrm.util.RestUtil;

import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.util.Arrays;

@Slf4j
@Component
public class RestTemplateUtil
{
    @Autowired
    private RestTemplate restTemplateOld;

    private static RestTemplate restTemplate;

    @PostConstruct
    public void init() {
        RestTemplateUtil.restTemplate = restTemplateOld;
    }

    /**
     * POST
     */
    public static ResponseEntity<String> jsonPost(String url, String json) {
        // TODO 频繁创建Header
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> requestEntity = new HttpEntity<String>(json, headers);
        ResponseEntity<String> entity = restTemplate.postForEntity(url, requestEntity, String.class);
        return entity;
    }


    /**
     * get请求
     *
     * @param url 路径
     * @param json 参数
     * @return
     */
    public static ResponseEntity<String> getRestTemplateGet(String url, String json) {
        HttpHeaders headers = new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        HttpEntity<String> requestEntity = new HttpEntity<String>(json, headers);
        ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class, requestEntity);
        return entity;
    }







    public static void main(String[] args) {
        final String resource = ClassUtils.getDefaultClassLoader().getResource("apiclient_key.pem").getPath();
        System.err.println(resource.substring(1, resource.length() - 1));

    }
}
